package edu.ccut.saturn.workflow.activity;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;

import edu.ccut.saturn.component.DefaultComponent;
import edu.ccut.saturn.component.IParameterContext;
import edu.ccut.saturn.component.SaturnData;
import edu.ccut.saturn.workflow.common.Constants;
import edu.ccut.saturn.workflow.common.Dom4jUtils;

public class SetActivityState extends DefaultComponent {
	@SuppressWarnings("unchecked")
	@Override
	public void execute(IParameterContext parameterContext) throws Exception {
		// 传入 byte[] xml
		// 传入 saturnlist
		byte[] xml = (byte[]) parameterContext.getParameterValue(0);
		List<SaturnData> saturnList = (ArrayList<SaturnData>) parameterContext
				.getParameterValue(1);

		InputStream in = null;
		try {
			xml = new String(xml, "GBK").getBytes("UTF-8");
			in = new ByteArrayInputStream(xml);
			Document document = Dom4jUtils.getDocment(in);
			Element root = document.getRootElement();
			List<Element> activityList = root.elements(Constants.ACTIVITY);

			for (SaturnData saturnData : saturnList) {
				String activity_defin_id = saturnData.get("activity_id") + "";
				Element act = getActivityElementbyId(activityList,
						activity_defin_id);
				addStateElement(act, saturnData.get("state") + "");
			}
			xml=document.asXML().getBytes("UTF-8");
		} catch (Exception e) {
		}finally{
			in.close();
		}
		parameterContext.setParameter(2, xml);
	}

	private Element getActivityElementbyId(List<Element> activityList,
			String activity_defin_id) {
		for(Element activityElement :activityList){
			if(activity_defin_id.equals(activityElement
			.attributeValue(Constants.ACTIVITY_ID))){
				return activityElement;
			}
		}
		return null;
	}

	private void addStateElement(Element activityElement, String state) {
		activityElement.addAttribute("state", state);
	}

}